package com.woniuxy.interceptor;

import com.woniuxy.annotation.RequirePermission;
import com.woniuxy.entity.Permission;
import com.woniuxy.entity.Emp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //        获取本次拦截的方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();
        Class<?> beanType = handlerMethod.getBeanType();

        log.debug("本次拦截的方法：{},{}", beanType.getName(), method.getName());
//        获取目标方法上的RequirePermission注解
        RequirePermission annotation = handlerMethod.getMethod().getAnnotation(RequirePermission.class);
//      如果RequirePermission不存在，说明方法不需要权限，放行
        if (annotation == null) {
            log.debug("{}没有RequirePermission注解，放行", method.getName());
            return true;
        }

//      如果有RequirePermission注解，那就从其中获取访问当前方法所需权限
        String perm = annotation.value();
        log.debug("{}需要权限：{}", method.getName(), perm);

//        获取当前用户所拥有的权限
        Emp loginEmp = (Emp) request.getSession().getAttribute("loginEmp");
        List<Permission> empPermissions = loginEmp.getPermissions();
//      判断用户所拥有的权限集合中，是否包含所需的权限
        List<String> stringPermissions = empPermissions
                .stream()
                .map(permission -> permission.getPermissionName())
                .collect(Collectors.toList());
        log.debug("当前用户拥有的权限：{}", stringPermissions);

        boolean contains = stringPermissions.contains(perm);
        if (!contains) {
            log.debug("用户没有所需权限，不放行");
            return false;
        }
        return contains;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
